package com.team622.shop.marketing.service.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.team622.shop.common.exceptions.BusinessException;
import com.team622.shop.common.exceptions.enums.Resp;
import com.team622.shop.marketing.model.entity.ActivityRule;
import com.team622.shop.marketing.service.mapper.ActivityRuleMapper;
import com.team622.shop.marketing.service.service.ActivityRuleService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author team622
 * @since 2025-07-16
 */
@Service
public class ActivityRuleServiceImpl extends ServiceImpl<ActivityRuleMapper, ActivityRule> implements ActivityRuleService {

    @Override
    @Transactional(rollbackFor = Exception.class)
    public ActivityRule addActivityRule(ActivityRule activityRule) {
        activityRule.setCreatedAt(new Date());
        activityRule.setUpdatedAt(new Date());

        this.save(activityRule);
        return activityRule;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean deleteActivityRule(Long id) {
        if (id == null) {
            throw new BusinessException(Resp.INVALID_PARAM);
        }
        return this.removeById(id);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public ActivityRule updateActivityRule(ActivityRule activityRule) {
        if (activityRule == null || activityRule.getId() == null) {
            throw new BusinessException(Resp.INVALID_PARAM);
        }
        activityRule.setUpdatedAt(new Date());
        this.updateById(activityRule);
        return activityRule;
    }

    @Override
    public ActivityRule getActivityRuleById(Long id) {
        if (id == null) {
            throw new BusinessException(Resp.INVALID_PARAM);
        }
        return this.getById(id);
    }

    @Override
    public Page<ActivityRule> pageActivityRule(Integer current, Integer pageSize,
                                             Long activityId, Integer ruleType) {
        LambdaQueryWrapper<ActivityRule> queryWrapper = new LambdaQueryWrapper<>();

        queryWrapper.eq(activityId != null, ActivityRule::getActivityId, activityId)
                .eq(ruleType != null, ActivityRule::getRuleType, ruleType);

        // 按创建时间倒序
        queryWrapper.orderByDesc(ActivityRule::getCreatedAt);

        return this.page(new Page<>(current, pageSize), queryWrapper);
    }
}

